#ifndef __EPOLL_H__
#define __EPOLL_H__
#include <iostream>
#include <sys/epoll.h>
#include "Log.hpp"

using namespace LogModule;

class Epoller
{
public:
    Epoller() : _epfd(-1)
    {
        _epfd = epoll_create(128);
        if (_epfd < 0)
        {
            LOG(LogLevel::DEBUG) << "epoll create failed!\n";
            exit(1);
        }
        LOG(LogLevel::INFO) << "epoll create success:" << _epfd;
    }
    void DelEvent(int sockfd)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
        (void)n;
    }
    void ModEventHelper(int sockfd,uint32_t events,int oper)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sockfd;
        int n = epoll_ctl(_epfd, oper, sockfd, &ev);
        if (n < 0)
        {
            LOG(LogLevel::DEBUG) << "epoll ctl error";
            return;
        }
        LOG(LogLevel::INFO) << "epoll ctl success";
    }
    void AddEvent(int sockfd, uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_ADD);
    }
    void ModEvent(int sockfd, uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_MOD);
    }
    int WaitEvents(struct epoll_event revs[], int maxnum, int timeout)
    {
        int n = epoll_wait(_epfd, revs, maxnum, timeout);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll wait error";
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "epoll wait timeout";
        }
        else
        {
            // 有事件就绪
        }
        return n;
    }

    ~Epoller()
    {
        if (_epfd >= 0)
            close(_epfd);
    }

private:
    int _epfd;
};
#endif